package com.baselib.libnetwork.net.base;

import com.baselib.libnetwork.net.HttpManager;

import java.io.IOException;

import okhttp3.MediaType;
import okhttp3.RequestBody;
import okio.Buffer;
import okio.BufferedSink;
import okio.ForwardingSink;
import okio.Okio;
import okio.Sink;

/**
 * @author lixuce
 * @version v1.0
 * @description
 * @since 2017/10/30
 */

public class ProgressRequestBody<T> extends RequestBody {

    private RequestBody requestBody;         //实际的待包装请求体
    private BaseCallback<T> callback;
    private BufferedSink bufferedSink;

    public ProgressRequestBody(RequestBody requestBody, BaseCallback<T> callback) {
        this.requestBody = requestBody;
        this.callback = callback;
    }

    /**
     * 重写调用实际的响应体的contentType
     */
    @Override
    public MediaType contentType() {
        return requestBody.contentType();
    }

    /**
     * 重写调用实际的响应体的contentLength
     */
    @Override
    public long contentLength() {
        try {
            return requestBody.contentLength();
        } catch (IOException e) {
            return -1;
        }
    }

    /**
     * 重写进行写入
     */
    @Override
    public void writeTo(BufferedSink sink) throws IOException {
        bufferedSink = Okio.buffer(sink(sink));
        //写入
        requestBody.writeTo(bufferedSink);
        //必须调用flush，否则最后一部分数据可能不会被写入
        bufferedSink.flush();
    }


    /**
     * 写入，回调进度接口
     *
     * @param sink Sink
     * @return Sink
     */
    private Sink sink(Sink sink) {
        return new ForwardingSink(sink) {
            //当前写入字节数
            long bytesWritten = 0L;
            //总字节长度，避免多次调用contentLength()方法
            long contentLength = 0L;

            @Override
            public void write(Buffer source, long byteCount) throws IOException {
                super.write(source, byteCount);
                if (contentLength == 0) {
                    //获得contentLength的值，后续不再调用
                    contentLength = contentLength();
                }
                //增加当前写入的字节数
                bytesWritten += byteCount;
                onProgress(bytesWritten * 1.0f / contentLength);
            }
        };
    }

    private void onProgress(final float progress) {
        HttpManager.getInstance().getDelivery().post(new Runnable() {
            @Override
            public void run() {
                if (callback != null) {
                    callback.onProgress(progress);
                }
            }
        });
    }

}
